package com.yangmin.springcloud.controller;

import com.yangmin.springcloud.entities.CommonResult;
import com.yangmin.springcloud.entities.Payment;
import com.yangmin.springcloud.lb.MyLoadBalance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class OrderController {
    //    private static final String paymentURL = "http://localhost:8001/";
    private static final String paymentURL = "http://CLOUD-PAYMENT-SERVICE";
    @Autowired
    private MyLoadBalance myLoadBalance;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/order/payment/creatPayment")
    public CommonResult<Integer> creatPayment(Payment payment) {
        return restTemplate.postForObject(paymentURL + "/add", payment, CommonResult.class);
    }

    @GetMapping("/order/payment/selectPayment/{id}")
    public CommonResult<Payment> selectPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(paymentURL + "/select/" + id, CommonResult.class);
    }


    @GetMapping("/order/getPort")
    public CommonResult<String> getPort() {
        return restTemplate.getForObject(paymentURL + "/getPort", CommonResult.class);
    }

    @GetMapping("/order/getPort2")
    public CommonResult<String> getPort2() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        ServiceInstance instance = myLoadBalance.getInstance(instances);
        return restTemplate.getForObject(instance.getUri() + "/getPort", CommonResult.class);
    }

    // =========zipkin
    @GetMapping("/payment/zipkin")
    public CommonResult<String> paymentZipkin() {
        return restTemplate.getForObject(paymentURL + "/payment/zipkin", CommonResult.class);
    }
}
